<?php
/**
 * Created by PhpStorm.
 * User: liujun
 * Date: 2017/11/7
 * Time: 下午5:26
 */
namespace PddWechat\Plugin;

use Dai\Framework\Base\BaseSessionInfo;
use Dai\Framework\Library\Log;
use Dai\Framework\Library\RedisExt;
use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\User\Plugin;
use PddWechat\Library\CookieLibrary;
use PddWechat\Library\WechatLibrary;
use PddWechat\Models\User\DataObject\UserDo;

/**
 * Class AuthPlugin
 * @package DaiBk\Plugin
 */
class AuthPlugin
{
    /**
     * 这个事件在dispatcher中的每个路由被执行前执行
     */
    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        $di = \Phalcon\DI::getDefault();
        /** @var \DaiBk\Models\Base\BasePageInfo $basePageInfo */
        $basePageInfo = $di->get('basePageInfo');

        $token = $di->get('cookies')->get(CookieLibrary::TOKEN)->getValue();

        if( $basePageInfo -> login == false){
            return;
        }

        /** @var UserDo $userInfo */
        $userInfo = null;
        if( $token != null) {
            $redisValue =  RedisExt::getInstance()->get($token);
            if($redisValue != null) {
                Log::info("token is [ $token ], redis [ $redisValue ]");
                /** @var UserDo $userInfo */
                $userInfo = json_decode($redisValue);
            }
        }

        //如果不需要登录
        if( $basePageInfo -> login == true && $userInfo ==null ){
            header("Location: " . WechatLibrary::getAuthRedirectLoginUrl($_SERVER["REQUEST_URI"], 123));exit;
        }

        if( $userInfo != null) {
            $sessionData = new BaseSessionInfo();
            $sessionData->uid = $userInfo->id;
            $sessionData->phone = $userInfo->mobile;
            $sessionData->openId = $userInfo->openId;
            $sessionData->userName = $userInfo->userName;
            $sessionData->nickName= $userInfo->realName;
            $sessionData->adminLevel = $userInfo->adminLevel;
            $sessionData->inviteCode = $userInfo->inviteCode;
            $basePageInfo->sessionInfo = $sessionData;

            $di->set('basePageInfo', function () use ($basePageInfo) { return $basePageInfo; });
        }
    }
}